# -*- coding: utf-8 -*-
"""
Web framework/Tornado WebSocket/test02/WebSocket Server.py
"""
import tornado.websocket
import tornado.web
import asyncio


class ServerHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin: str) -> bool:
        """
        WebSocketHandler.check_origin
        :param origin:
        :return:
        """
        return True

    def open(self):
        """
        WebSocketHandler.open
        :return:
        """
        r_message = f"WebSocket Opened."
        print(r_message)
        self.write_message(r_message)

    def on_message(self, message):
        """
        WebSocketHandler.on_message
        :param message:
        :return:
        """
        r_message = f"Your send message is {message}."
        print(r_message)
        self.write_message(r_message)

    def on_close(self) -> None:
        """
        WebSocketHandler.on_close
        :return:
        """
        print("WebSocket Closed.")

    def on_ping(self, data: bytes) -> None:
        """
        WebSocketHandler.on_ping
        :return:
        """
        self.ping(data=data)
        print("WebSocket Ping.")

    def on_pong(self, data: bytes) -> None:
        """
        WebSocketHandler.on_pong
        :return:
        """
        print(f"WebSocket Pong.{data}")


async def main():
    app = tornado.web.Application([
        (r"/websocket/", ServerHandler),
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
